package com.my.library.entity;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import org.springframework.jdbc.core.RowMapper;

import com.my.library.util.EntityTableMapping;

public class EntityRowMapper<T> implements RowMapper<T> {

		private Class<T> entity;
		private String[] fields;
		public EntityRowMapper(Class<T> entity, String[] fields) {
			super();
			this.entity = entity;
			this.fields = fields;
		}
		@Override
		public T mapRow(ResultSet rs, int index) throws SQLException {
			T t = null;
			try {
				t = entity.newInstance();
				/*entity.getMethod("setId", int.class).invoke(t, rs.getInt("id"));
				for(String field: fields) {
					entity.getMethod("set" + StringUtil.getFirstUpperName(field), String.class).invoke(t, rs.getString(field) == null ? "" : rs.getString(field));
				}*/
				for(Field f: entity.getDeclaredFields()) {
					String fieldName = EntityTableMapping.getTableOrFieldName(f);
					for(String field: fields) {
						if(fieldName.equals(field)) {
							f.setAccessible(true);
							Class<?> type = f.getType();
							if(type == String.class) {
								f.set(t, rs.getString(field));
							} else if(type == Integer.class || type == int.class) {
								f.set(t, rs.getInt(field));
							} else if(type == Date.class || type == java.sql.Date.class) {
								f.set(t, rs.getDate(field));
							} else if(type == Timestamp.class) {
								f.set(t, rs.getTimestamp(field));
							}
							break;
						}
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return t;
		}
		
	}
